package com.atguigu.flow.utils;

import com.atguigu.flow.entity.Leaf;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Component
public
class XmlTest {
    private static List<Leaf> elemList = new ArrayList<Leaf>();
    public String xmltest(String srcXml) throws DocumentException {
       // XmlTest test = new XmlTest();
        Element root = getRootElement(srcXml);
        getElementList(root);
        String x = getListString(elemList);
        return x;
    }

    public
    Element getRootElement(String srcXml ) throws DocumentException {
        Document srcdoc = DocumentHelper.parseText(srcXml);
        Element elem = srcdoc.getRootElement();
        return elem;
    }
    public void getElementList(Element element) {
        List elements = element.elements();
        if (elements.size() == 0) {
            //没有子元素
            String xpath = element.getPath();
            String value = element.getTextTrim();
            Leaf leaf=new Leaf();
            leaf.setValue(value);
            leaf.setXpath(xpath);
            elemList.add(leaf);
        } else {
            //有子元素
            for (Iterator it = elements.iterator(); it.hasNext();) {
                Element elem = (Element) it.next();
                //递归遍历
                getElementList(elem);
            }
        }
    }

    public String getListString(List<Leaf> elemList) {
        StringBuffer sb = new StringBuffer();
        for (Iterator<Leaf> it = elemList.iterator(); it.hasNext();) {
            Leaf leaf = it.next();
            sb.append(leaf.getXpath()).append( " = ").append(leaf.getValue()).append( "\n");
        }
        return sb.toString();
    }

}
